#! /bin/bash

usage()
{
    echo "usage: $0 {get | set <version>}"
    exit 1
}


set +x
if [[ $# < 1 ]]
then
    usage
fi

version_str='__version__ ='

case "$1" in
    get)
        (
        for f in $(find src tools -type f -exec grep -l "$version_str" {} \;)
        do
            echo -n "$f: "
            grep "$version_str" $f
        done
        echo -n "setup.py: "
        grep version setup.py
        ) | awk "
            BEGIN { FS = \"[=:]+\"; max=-1 };
            { gsub(/[,' ]+/, \"\", \$NF); files[NR]=\$1; v=\$NF; versions[NR]=v; if (v > max) max=v;}
            END {
                for (i in files) {
                    if (versions[i] == max) {
                        s=\" MAX\"
                    } else {
                        s = \"\"};
                    printf(\"%-45s: %s%s\\n\", files[i], versions[i], s)};
            }
            "
        ;;

    set)
        if [[ $# != 2 ]]
        then
            usage
        fi
        version="$2"
        for f in $(find src tools -type f -exec grep -l "$version_str" {} \;)
        do
            echo "<<< $f >>>"
            case "$(uname)" in
                Darwin)
                    sed -E -i '' -e "s@$version_str \'[0-9abr.]+\'@$version_str \'$version\'@" $f
                    ;;

                Linux)
                    sed -E -i -e "s@$version_str '[0-9abr.]+'@$version_str '$version'@" $f
                    ;;
            esac
        done

        echo "<<< setup.py >>>"
        case "$(uname)" in
            Darwin)
                sed -E -i '' -e "s@version='[0-9abr.]+'@version='$version'@" setup.py
                ;;

            Linux)
                sed -E -i -e "s@version='[0-9abr.]+'@version='$version'@" setup.py
                ;;
        esac
        ;;
 esac
